package com.edu.swu.dao.imp;

import com.edu.swu.dao.IAccountDao;
import com.edu.swu.domain.Account;
import com.edu.swu.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;
//注解的Dao不能继承JdbcDaoSupport类
public class AccountDaoImp implements IAccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public Account findById(Integer accountId) {
       List<Account> accounts =jdbcTemplate.query("select * from user_demo where id = ?",new BeanPropertyRowMapper<Account>
               (Account.class),accountId);
       return accounts.isEmpty()?null:accounts.get(0);
    }

    public Account findByName(String acountName) {
        List<Account> accounts=jdbcTemplate.query("select * from user_demo where username = ?",new BeanPropertyRowMapper<Account>(Account.class),
                acountName);
        if(accounts==null)
            return null;
        if(accounts.size()>1)
            throw new RuntimeException("查询数据不唯一");
        return accounts.get(0);
    }

    public void updateAccount(Account account) {
        jdbcTemplate.update("update user_demo set userAge = ? where id = ?",account.getUserAge(),account.getId());
    }
}
